package cn.highset.modules.base.controller.manage;

import cn.highset.common.exception.HighsetException;
import cn.highset.common.utils.ResultUtil;
import cn.highset.common.vo.Result;
import cn.highset.modules.base.entity.ProductType;
import cn.highset.modules.base.factory.ProductTypeFactory;
import cn.highset.modules.base.service.ProductTypeService;
import cn.highset.redis.client.RedisClient;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * @author Victor
 */
@Slf4j
@RestController
@Api(description = "产品类别管理接口")
@RequestMapping("/highset/productType")
@Transactional
public class ProductTypeController {

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private RedisClient redisClient;

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部产品类别")
    public Result<Object> all() {
//        List<ProductType> list = productTypeService.findByParentIdOrderBySortOrder("0");
//        if (CollUtil.isNotEmpty(list)) {
//            for (ProductType parent : list) {
//                parent.setChildren(productTypeService.findByParentIdOrderBySortOrder(parent.getId()));
//            }
//        }

        return new ResultUtil<Object>().setData(getAll("0"));
    }


    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加")
    public Result<Object> add(@ModelAttribute ProductType o) {
        if (StrUtil.hasBlank(o.getNameCn(), o.getNameEn())) {
            return new ResultUtil<Object>().setErrorMsg("缺少必需表单字段");
        }
        setLevels(o);
        ProductType bean = productTypeService.save(o);
        if (bean == null) {
            return new ResultUtil<Object>().setErrorMsg("添加失败");
        }
        // 手动删除所有产品类别缓存
        redisClient.key().del(redisClient.key().keys("productType:" + "*"));
        return new ResultUtil<Object>().setSuccessMsg("添加成功");
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiOperation(value = "编辑")
    public Result<Object> edit(@ModelAttribute ProductType o) {
        if (StrUtil.hasBlank(o.getId(), o.getNameCn(), o.getNameEn())) {
            return new ResultUtil<Object>().setErrorMsg("缺少必需表单字段");
        }
        ProductType old = productTypeService.get(o.getId());
        ProductType type = ProductTypeFactory.edit(o, old);
        setLevels(type);
        ProductType bean = productTypeService.update(type);

        if (bean == null) {
            return new ResultUtil<Object>().setErrorMsg("修改失败");
        }
        updateChildren(bean.getId());
        // 手动删除所有产品类别缓存
        redisClient.key().del(redisClient.key().keys("productType:" + "*"));
        return new ResultUtil<Object>().setSuccessMsg("编辑成功");
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    public Result<Object> delByIds(@PathVariable String[] ids) {

        for (String id : ids) {
            productTypeService.delete(id);
        }
        // 手动删除所有产品类别缓存
        redisClient.key().del(redisClient.key().keys("productType:" + "*"));
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }


    @RequestMapping(value = "/getByParentId/{parentId}", method = RequestMethod.GET)
    @ApiOperation(value = "通过parentId获取")
    public Result<List<ProductType>> getByParentId(@PathVariable String parentId) {

        return new ResultUtil<List<ProductType>>().setData(productTypeService.findByParentIdOrderBySortOrder(parentId));
    }


    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ApiOperation(value = "类别中文名称模糊搜索")
    public Result<List<ProductType>> searchByNameCn(@RequestParam String nameCn) {

        List<ProductType> list = productTypeService.findByNameCnLikeOrderBySortOrder("%" + nameCn + "%");
        list = productTypeService.setInfo(list);
        return new ResultUtil<List<ProductType>>().setData(list);
    }
    /**
     * 根据请求的父级类别id设置parentId和层级
     */
    private void setLevels( ProductType t) {
        if (StrUtil.isBlank(t.getParentId()) || "0".equals(t.getParentId())) {
            t.setParentId("0");
            t.setParentIds("[0],");
            t.setLevels(1);
        } else {
            String parentId = t.getParentId();
            ProductType pType = productTypeService.get(parentId);

            Integer pLevels = pType.getLevels();

            //如果id和父id一致会导致无限递归
            if (t.getId().equals(t.getParentId())) {
                throw new HighsetException("类别id和上级id不能一致");
            }

            t.setLevels(pLevels + 1);
            t.setParentIds(pType.getParentIds()+ "[" + pType.getId() + "],");
        }
    }

    /**
     * 更新子类别
     * @param parentId
     */
    private void updateChildren(String parentId){
    List<ProductType> list = productTypeService.findByParentIdOrderBySortOrder(parentId);
        for (Iterator<ProductType> it = list.iterator(); it.hasNext(); ) {
            ProductType type =  it.next();
            setLevels(type);
            productTypeService.update(type);
            updateChildren(type.getId());

        }
    }

    /**
     * 获取全部类别
     */
    private List<ProductType> getAll(String parentId){
        List<ProductType> list = productTypeService.findByParentIdOrderBySortOrder(parentId);
        if(CollUtil.isNotEmpty(list)){
            for (ProductType type:list
                 ) {
                type.setChildren(getAll(type.getId()));
            }
        }
        return list;
    }

}
